<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <l-panel>
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入关键字查询')"
            v-model="searchWord"
            @keyup.enter.native="hanleSearch"
            size="mini"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="hanleSearch"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()" :refreshClick="refreshClick">
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        :loading="tableLoading"
        :columns="lr_getPageColumns(columns)"
        :dataSource="tableData"
        row-key="f_Id"
      >
        <l-table-btns
          :filterBtns="filterBtns"
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>

    <l-dialog
      :title="formTitle"
      :visible.sync="formVisible"
      :height="576"
      ref="formDialog"
      @opened="handleOpenedForm"
      @closed="handleCloseForm"
      @ok="handleSave"
    >
      <my-form ref="form" :activeName.sync="activeName"></my-form>
      <template #btn>
        <el-button
          style="position: absolute;left: 0;top:9px;"
          size="mini"
          type="info"
          plain
          @click="handleTest"
          :loading="testLoading"
          
          >{{ $t("测试连接") }}</el-button
        >
      </template>
    </l-dialog>
  </l-layout>
</template>

<script>
const api = window.$api.data.dblink;
import MyForm from "./form";

export default {
  components: {
    MyForm,
  },
  data() {
    return {
      lr_isPage: true,
      // 表格
      columns: [
        { label: "名称", prop: "f_DBAlias", minWidth: "150" },
        { label: "编码", prop: "f_DBName", minWidth: "150" },
        { label: "类型", prop: "f_DbType", width: "80", align: "center" },
        { label: "数据库地址", prop: "f_ServerAddress", width: "200" },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑", width: 40 },
        { prop: "Delete", label: "删除", width: 40 },
      ],
      tableLoading: false,
      searchWord: "",
      searchTableData: null,

      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      testLoading: false,
      activeName: "first",
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    tableData() {
      return this.searchTableData || this.lr_dblinkList;
    },
  },
  methods: {
    refreshClick() {
      this.searchWord = "";
      this.init();
    },

    async init() {
      this.tableLoading = true;
      await this.lr_loadDblink(false);
      this.tableLoading = false;
    },

    hanleSearch() {
      if (this.searchWord) {
        this.searchTableData = this.lr_dblinkList.filter(
          (item) =>
            item.f_DBAlias.indexOf(this.searchWord) > -1 ||
            item.f_DBName.indexOf(this.searchWord) > -1 ||
            (item.f_ServerAddress &&
              item.f_ServerAddress.indexOf(this.searchWord) > -1)
        );
      } else {
        this.searchTableData = null;
      }
    },
    // 表单部分
    handleAdd() {
      this.$refs.form && this.$refs.form.resetForm();
      this.activeName = "first";
      this.formEdit = false;
      this.showForm("新增");
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.activeName = row.f_Type == 0 ? "first" : "second";
      this.showForm(`编辑【${row.f_DBName}】`);
    },
    handleDelete($index, row) {
      this.$confirm(
        this.$t("此操作将永久删除该数据, 是否继续?"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(() => {
          api.remove(row.f_Id).then(() => {
            this.$message({
              type: "success",
              message: this.$t("删除成功!"),
            });
            this.init();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除"),
          });
        });
    },
    handleSave(showLoading,hideLoading) {
      showLoading();
      console.log("test handleSave")
      this.$refs.form.validateForm((valid) => {
        if (valid) {
          const formData = this.$refs.form.getForm();
          console.log("test handleSave1")
          if (this.formEdit) {
            // 修改数据
            api
              .update(formData.f_Id, this.$deepClone(formData))
              .then(() => {
                hideLoading();
                this.formVisible = false;
                this.$message({
                  type: "success",
                  message: this.$t("更新成功!"),
                });
                this.init();
              })
              .catch(() => {
                hideLoading();
              });
          } else {
            // 新增数据
            api
              .add(this.$deepClone(formData))
              .then(() => {
                hideLoading();
                this.formVisible = false;
                this.$message({
                  type: "success",
                  message: this.$t("添加成功!"),
                });
                this.init();
              })
              .catch(() => {
                hideLoading();
              });
          }
        } else {
          hideLoading();
        }
      });
    },
    handleOpenedForm() {
      if (this.formEdit) {
        this.$refs.form.setForm(this.formEditRow);
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },

    filterBtns(row, btns) {
      if (row.f_DBName != "lrsystemdb" && row.f_IsEdit != 0) {
        return btns;
      } else {
        return [];
      }
    },
    //数据连接测试
    handleTest() {
      const formData = this.$refs.form.getForm();
      if ((formData.f_Type !=0 && !formData.f_DbConnection) || (formData.f_Type == 0 &&(!formData.f_Server || !formData.f_Port || !formData.f_UserId || !formData.f_Password))) {
        this.$message({
          type: "error",
          message: this.$t("请将数据库信息补充完整!"),
        });
        return;
      }
      this.testLoading = true;
      api
        .test(formData)
        .then((res) => {
          if (res.data.data) {
            this.$message({
              type: "success",
              message: this.$t("测试成功!"),
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.info,
            });
          }
          this.testLoading = false;
        })
        .catch(() => {
          this.testLoading = false;
        });
    },
  },
};
</script>
